// const { loginVerify } = require("../../utils/login")

import {handleUrlParams, requestSubscribeMessage} from "../../utils/util";
import urlUtils from "../../utils/urlUtils";

const app = getApp()

let timer = null

Page({
	data: {
		isShowNotice: false,
		nitoceText: "...",
		isShowView: false,
		enable: 0, // 学校是否开启小程序 0为启用 1为关闭
		appMsg: {
			show: false,
			type: "loading",
		},
		picUrlArr: [],
		iconx3: "../../assets/images/index-icon/iconx3.png",
		navData: [
			// 常用模块
			{
				name: "课表",
				img: "/assets/images/index-icon/1@x3.png",
				url: "/pages/schoolStudy/schedule/index",
			},
			{
				name: "查成绩",
				img: "/assets/images/index-icon/2@x3.png",
				url: "/pages/schoolStudy/exam/exam",
			},
			{
				name: "电子成绩单",
				img: "/assets/images/index-icon/7@x3.png",
				url: "/pages/workService/electronicReportCard/index",
			},
			{
				name: "电子证明",
				img: "/assets/images/index-icon/8@x3.png",
				url: "/pages/workService/electronicFile/electronicFile",
			},
		],
		menuData: [],
		identityType: "", //判断身份是否是教师，学生
		isRed: true,
		headlineCountObj: {
			isShow: false,
			status: 0, // 0不显示  1表示10以内  2表示10以上一百以内 3表示一百以上
			text: 0,
		}, // 头条未读
		lectureCountObj: {
			isShow: false,
			status: 0, // 0不显示  1表示10以内  2表示10以上一百以内 3表示一百以上
			text: 0,
		}, // 公益讲坛未读
		visiblePwdSelect: false,
		actions: [
			{ name: "人证验证", type: 1, color: "#2172ed" },
			{ name: "手机验证", type: 2, color: "#2172ed" },
		],
		popupConfig: {
			imageUrl: "",
			intervalTime: "",
			isEnable: "",
			requestUrl: "",
			schoolCode: "",
			schoolName: "",
			title: null,
		},
		showPopup: false,
		countDown: 10,
		timer: null,
		showReadPoint: false,
		animation: "",
		animationData: "",
		indicatorDots: false,
		autoplay: true,
		interval: 3000,
		duration: 500,
	},
	onClick(e) {
		let row = this.data.actions[e.detail.index]
		console.log("点击某个按钮", row)
		if (row.type === 1) {
			wx.reLaunch({
				url: "/pages/person/swtp/swtp",
			})
		} else if (row.type === 2) {
			wx.reLaunch({
				url: "/pages/person/phonePwd/phonePwd",
			})
			console.log("手机验证码修改密码")
		}
	},
	/**
	 * @see 获取校务头条和公益讲坛未读消息
	 */
	getIsClicksHeadlineRecord() {
		wx.$API["home/isClicksHeadlineRecord"]({}).then((res) => {
			const { headlineCountObj, lectureCountObj } = this.data
			let { headlineCount, lectureCount } = res
			// headlineCount = 100
			if (headlineCount > 99) {
				headlineCountObj.text = "···"
				headlineCountObj.isShow = true
				headlineCountObj.status = 3
			} else if (headlineCount >= 10 && headlineCount <= 99) {
				headlineCountObj.text = headlineCount
				headlineCountObj.isShow = true
				headlineCountObj.status = 2
			} else if (headlineCount > 0 && headlineCount < 10) {
				headlineCountObj.text = headlineCount
				headlineCountObj.isShow = true
				headlineCountObj.status = 1
			} else {
				headlineCountObj.isShow = false
				headlineCountObj.status = 0
			}
			if (lectureCount > 99) {
				lectureCountObj.text = "···"
				lectureCountObj.isShow = true
				lectureCountObj.status = 3
			} else if (lectureCount >= 10 && lectureCount <= 99) {
				lectureCountObj.text = lectureCount
				lectureCountObj.isShow = true
				lectureCountObj.status = 2
			} else if (lectureCount > 0 && lectureCount < 10) {
				lectureCountObj.text = lectureCount
				lectureCountObj.isShow = true
				lectureCountObj.status = 1
				lectureCountObj.text = lectureCount
			} else {
				lectureCountObj.isShow = false
				lectureCountObj.status = 0
			}
			this.setData({
				headlineCountObj,
				lectureCountObj,
			})
		})
	},

	/**
	 * @see 监听右上角菜单“分享到朋友圈”按钮的行为
	 */
	onShareTimeline(res) {
		// return {
		//   title: '测试标题',
		//   query: 'a=1&b=2',
		//   imageUrl: 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/index-icon/35@x3.png'
		// }
	},
	/**
	 * @see 分享
	 */
	onShareAppMessage(res) {
		return {
			title: "校务行",
			path: "/pages/home/index",
		}
	},
	onLoad(option) {
		if (option.isCheckLogin === "true") {
			// 真伪验证跳转回首页要验证是否登录
			app.loginVerify()
		}
		this.initView()
		// this.getPosterConfig()
		// this.getIsClicksHeadlineRecord()
		// 创建动画实例(animation)
		var animation = wx.createAnimation({
			duration: 500, //动画持续时间
			timingFunction: "ease", //动画以低速开始
			//具体配置项请查看文档
		})
		// 建立标识(用于循环)
		this.animation = animation
		var next = true
		// 无限循环动画
		timer = setInterval(
			function () {
				if (next) {
					// 你要执行动画链(详见文档)
					this.animation.scale(0.8).step()
					// -----------------------
					next = !next
				} else {
					// 你要执行动画链(详见文档)
					this.animation.scale(1.1).step()
					// -----------------------
					next = !next
				}
				// 导出动画
				this.setData({
					animationData: animation.export(),
				})
			}.bind(this),
			500,
		)
	},
	getPosterConfig() {
		wx.$API["login/getPosterConfig"]()
			.then((res) => {
				wx.setStorage("posterConfig", res.data)
				if (res.data.openAdvertising) {
					setTimeout(() => {
						wx.navigateTo({
							url: "/pages/getPhone/getPhone",
						})
						console.log("开广告")
					}, 300)
				}
				console.log(res, "广告开关配置")
			})
			.catch((error) => {
				console.log(error, "获取 广告开关配置 失败")
			})
	},

	// 关闭弹框
	closePopup() {
		this.setData({
			showPopup: false,
			countDown: 10,
		})
	},
	// 跳转弹框页面
	openPopupPage() {
		wx.$API["home/addHitsBySchoolCode"]()
			.then((res) => {
				console.log(res, "点击量+1")
			})
			.catch((error) => {
				console.log(error, "点击量错误 ")
			})
		if (this.data.popupConfig.requestUrl) {
			this.setData({
				showPopup: false,
			})
			if (this.data.popupConfig.requestUrl === "gzfw") {
				let gzfwdata = {
					schoolCode: wx.getStorageSync("schoolConfig").schoolCode,
					userId: wx.getStorageSync("userInfo").userId,
					origin: "xwx",
				}
				console.log(gzfwdata, "这是跳转公证服务带的参数")
				wx.navigateToMiniProgram({
					appId: "wx3b45a1e961170bfc",
					path: "/pages/home/home",
					extraData: gzfwdata,
				})
			} else if (
				["zwy"].includes(this.data.popupConfig.requestUrl) ||
				this.data.popupConfig.appid
			) {
				this.openZlzp(this.data.popupConfig)
			} else {
				wx.navigateTo({
					url: this.data.popupConfig.requestUrl,
				})
			}
		} else {
			wx.previewImage({
				urls: [this.data.popupConfig.imageUrl],
				current: 1,
			})
		}
	},
	openZlzp({ requestUrl, appid, envVersion }) {
		let schoolConfig = wx.getStorageSync("schoolConfig")
		let userInfo = wx.getStorageSync("userInfo")
		if (requestUrl) {
			if (requestUrl.indexOf("?") !== -1) {
				requestUrl += `&schoolCode=${schoolConfig.schoolCode}&studentNumber=${userInfo.userId}`
			} else {
				requestUrl += `?schoolCode=${schoolConfig.schoolCode}&studentNumber=${userInfo.userId}`
			}
		}
		// let path = `/packageResume/activityNineResume/activityNineResume?activityShareId=7275&utm_source=9resume&refer=5004014&utm_campaign=xiaowuxing&schoolCode=${schoolConfig.schoolCode}&studentNumber=${userInfo.userId}`
		// console.log(requestUrl, 'path')
		wx.navigateToMiniProgram({
			appId: appid,
			path: requestUrl,
			envVersion: envVersion,
		})
	},
	getAdvertisementBySchoolCode() {
		console.log("函数执行")
		wx.$API["home/getAdvertisementBySchoolCode"]()
			.then((res) => {
				console.log(res, "获取学校的弹窗信息")
				let item = res.data[0]
				let prevPopupTime = wx.getStorageSync("prevPopupTime")
				// let h = 360
				let h = 3600000 // 一小时
				function isShowPopup() {
					if (item.isEnable === "false") {
						console.log("学校没有开广告")
						wx.removeStorage({key:"prevPopupTime"})
						return false
					}
					if (!prevPopupTime || item.intervalTime === "0") {
						console.log("第一次展示弹框")
						// 保存现在弹框的时间,n小时内不再弹出
						wx.setStorage({ key: "prevPopupTime", data: +new Date() })
						return true
					} else if (+new Date() - prevPopupTime > item.intervalTime * h) {
						console.log("超过间隔时间,重新显示弹框")
						return true
					}
					console.log("不符合展示弹框的条件,不展示")
					return false
				}
				this.setData(
					{
						popupConfig: res.data[0],
						showPopup: isShowPopup(),
					},
					() => {
						if (this.data.showPopup) {
							clearInterval(this.data.timer)
							this.data.timer = setInterval(() => {
								let countDown = this.data.countDown - 1
								if (countDown <= 0) {
									clearInterval(this.data.timer)
									this.setData({
										showPopup: false,
										countDown: 10,
									})
								} else {
									this.setData({
										countDown,
									})
								}
							}, 1000)
						}
					},
				)
			})
			.catch((error) => {
				console.log(error, "error")
				wx.showToast({
					title: error,
					icon: "none",
				})
			})
	},
	wzxyOpen() {
		if (app.globalData.from === "WZXY" && app.globalData.app === "file") {
			console.log(
				"从[我在校园跳转过来]在[首页]页面进入文件代办",
				app.globalData.from,
			)
			wx.navigateTo({
				url: "/pages/web/web?Dfrom=WZXY&path=https://xwx.gzzmedu.com/file-agency",
				success() {
					app.globalData.from = ""
					app.globalData.app = ""
				},
			})
		}
	},
	showActionType() {
		console.log(app.globalData.from, app.globalData.actionType)
		if (app.globalData.actionType === "zp" /*智联招聘*/) {
			wx.navigateTo({
				url: "/pages/themePage/themePage",
			})
			// wx.showModal({
			//   title: '提示',
			//   content: '即将跳转“智联校园”查看',
			//   success(res) {
			//     app.globalData.actionType = ''
			//     let schoolConfig = wx.getStorageSync('schoolConfig')
			//     let userInfo = wx.getStorageSync('userInfo')
			//     if (res.confirm) {
			//       if (schoolConfig.param1) {
			//         if (schoolConfig.param1.indexOf('?') !== -1) {
			//           schoolConfig.param1 += `&schoolCode=${schoolConfig.schoolCode}&studentNumber=${userInfo.userId}`
			//         } else {
			//           schoolConfig.param1 += `?schoolCode=${schoolConfig.schoolCode}&studentNumber=${userInfo.userId}`
			//         }
			//       }
			//       console.log(schoolConfig.param1, '这是跳转智联招聘的url')
			//       wx.navigateToMiniProgram({
			//         appId: 'wx08e25a163d60852c',
			//         path: schoolConfig.param1,
			//         success: () => {},
			//       })
			//       console.log('用户点击确定')
			//     } else if (res.cancel) {
			//       console.log('用户点击取消')
			//     }
			//   },
			// })
		}
	},

	onShow(options) {
		const token = wx.getStorageSync("token")
		if (token) {
			this.getChangePwdStatus()
			this.tiktokUrlScheme()
			this.showActionType()
		} else {
			// loginVerify()
		}
		this.getIsClicksHeadlineRecord()
		this.refreshRedPoint()
	},
	onUnload() {
		// app.afterLoginCallback = null
		clearInterval(this.data.timer)
		clearInterval(timer)
	},
	tiktokUrlScheme() {
		if (app.globalData.from === "TikTokSms") {
			wx.navigateTo({
				url: "/pages/web/web?path=https://xwx.gzzmedu.com/advertising",
				success() {
					app.globalData.from = ""
				},
			})
			return
		}
	},
	//  重置 暑期技能提升 红点状态
	refreshRedPoint() {
		let time = wx.getStorageSync("sqjnts")
		let cod = false
		if (!time || +new Date() - time > 1000 * 60 * 60 * 5) {
			console.log("显示红点")
			cod = true
		} else {
			cod = false
		}
		this.setData({
			showReadPoint: cod,
		})
		// wx.setStorage({ key: 'sqjnts', data: +new Date() })
	},
	getChangePwdStatus() {
		const status = wx.getStorageSync("changePwdStatus")
		// if (status && !status.isSkipChangePwd) {
		//   console.log('不获取!')
		//   return
		// }
		wx.$API["home/changePwdEnable"]()
			.then((res) => {
				wx.setStorageSync("changePwdStatus", { ...res })
				console.log("获取一下是否要修改密码", res)
				if (!res.isSkipChangePwd) return
				if (res.changePwdType === 0) {
					console.log("选择验证方式")
					this.setData({
						visiblePwdSelect: true,
					})
				} else if (res.changePwdType === 1) {
					console.log("人证验证方式")
					wx.reLaunch({
						url: "/pages/person/swtp/swtp", // 为了过审核,在app.json中删掉了
					})
				} else if (res.changePwdType === 2) {
					console.log("短信验证方式")
					wx.reLaunch({
						url: "/pages/person/phonePwd/phonePwd",
					})
				}
			})
			.catch((error) => {
				console.log(error, "error?????是这里?")
			})
	},
	/**
	 * @see 初始化视图（防止页面一闪而过）
	 */
	initView() {
		const token = wx.getStorageSync("token")
		if (token) {
			this.getMenu()
			this.getNotice()
			app.getTemplateIds()
			this.getAdvertisementBySchoolCode()
			this.wzxyOpen()
		} else {
			app.afterLoginCallbackList.push((res) => {
				this.getMenu()
				this.getNotice()
				app.getTemplateIds()
				this.getChangePwdStatus()
				this.getAdvertisementBySchoolCode()
				this.wzxyOpen()
			})
		}
	},
	/**
	 * @see 获取公告
	 */
	getNotice() {
		wx.$API["home/getNotice"]({})
			.then((result) => {
				const { data } = result
				if (data.length) {
					const noticeCache = wx.getStorageSync("noticeCache")
					const { createTime, noticeId, close } = noticeCache
					const noticeObj = data[0]
					if (
						createTime === noticeObj.createTime &&
						noticeId === noticeObj.noticeId &&
						close
					) {
						this.setData({
							isShowNotice: false,
						})
					} else {
						this.setData({
							isShowNotice: true,
							nitoceText: noticeObj.content,
						})
						wx.setStorage({
							key: "noticeCache",
							data: {
								createTime: noticeObj.createTime,
								noticeId: noticeObj.noticeId,
								close: false,
							},
						})
						// wx.setStorageSync('noticeCache', {
						//   createTime: noticeObj.createTime,
						//   noticeId: noticeObj.noticeId,
						//   close: false,
						// })
					}
				} else {
					this.setData({
						isShowNotice: false,
					})
				}
			})
			.catch((err) => {
				this.setData({
					isShowNotice: false,
				})
			})
	},

	/**
	 * @see 推送模板消息
	 */
	openShcoolHeadLine(e) {
		const { enable } = this.data
		const url = e.currentTarget.dataset.item.url
		const item = e.currentTarget.dataset.item
		wx.setStorage({
			key: "currentMenu",
			data: e.currentTarget.dataset.item,
		})
		const request = {
			menuId: e.currentTarget.dataset.menuid,
		}
		// 点击率统计
		wx.$API["home/addRecord"](request).catch((err) => {
			console.log(err)
		})
		// jumpType 跳转类型（Applet 小程序,Instation 站内页面,H5	H5页面,NONE 无） url 跳转路径 appid 
		const urlObj = urlUtils.parseUrl(item.url)
		// 获取当前的小程序版本，开发板跳开发板，体验版跳体验版，正式版跳正式版
		const envVersion = wx.getAccountInfoSync().miniProgram.envVersion
		switch (item.jumpType) {
			case "Applet":
				wx.navigateToMiniProgram({
					appId: item.appid,
					// 插入来源学校参数
					path: handleUrlParams(
						urlObj.path,
						{
							...urlObj.query,
							XWX_schoolName_7p4t: wx.getStorageSync("schoolConfig").schoolName,
						}
					),
					envVersion: envVersion,
				})
				return
			case "Instation":
				wx.navigateTo({
					url: item.url,
				})
				return
			case "H5":
				wx.navigateTo({
					url: `/pages/web/web?path=${item.url}`,
				})
				return
		}
		
		if (enable === 0) {
			if (url === "YZM") {
				let extraData = {
					uid: wx.getStorageSync("userInfo").userId,
					sid: app.globalData.YZM.sid,
					origin: "ZM",
				}
				console.log(extraData, "打开 印之梦 小程序,跳转参数")
				// 跳转到印之梦小程序
				wx.navigateToMiniProgram({
					appId: "wx1badb88b489408bb",
					path: "pages/loading/index",
					extraData: extraData,
					success(res) {},
				})
			} else if (url === "ky") {
				wx.navigateToMiniProgram({
					appId: "wx37094462a9ee7301",
					path: "/pages/exercises/list?id=1470944926071840770",
				})
			} else if (url === "gzfw") {
				let gzfwdata = {
					schoolCode: wx.getStorageSync("schoolConfig").schoolCode,
					userId: wx.getStorageSync("userInfo").userId,
					origin: "xwx",
				}
				console.log(gzfwdata, "这是跳转公证服务带的参数")
				wx.navigateToMiniProgram({
					appId: "wx3b45a1e961170bfc",
					path: "/pages/home/home",
					extraData: gzfwdata,
				})
			} else if (["jlmb", "cp", "kc", "zpld"].includes(url)) {
				wx.setStorage({ key: "sqjnts", data: +new Date() })
				app.openZlzp(url)
			} else if (url === "zlzp") {
				let schoolConfig = wx.getStorageSync("schoolConfig")
				console.log(schoolConfig)
				this.openZlzp({
					requestUrl: schoolConfig.param1,
					appid: "wx08e25a163d60852c",
				})
			} else {
				wx.navigateTo({
					// url,
					url:
						url.indexOf("?") !== -1
							? `${url}&eventType=click`
							: `${url}?eventType=click`,
				})
			}
		} else {
			wx.showModal({
				title: "提示",
				content: "暂未开放",
				complete: (msg) => {
					console.log(msg)
				},
			})
			return
		}
		if (
			e.currentTarget.dataset.item.menuId ===
			"29aeff83-c8b7-4f63-b1bb-280caa57d22a"
		) {
			wx.requestSubscribeMessage({
				tmplIds: app.globalData.tmplIds.slice(0, 3),
				success() {
					requestSubscribeMessage()
				},
				complete: (msg) => {
					console.log("获取模板消息推送权限:", msg)
					//将用户接受订阅的消息提交给后台
				},
			})
		} else if (e.currentTarget.dataset.item.isAnimation === "true") {
			wx.setStorage({ key: "sqjnts", data: +new Date() })
			console.log("点击了暑期技能提升")
		}
	},

	/**
	 * @see 获取菜单
	 */
	getMenu() {
		this.setData({
			appMsg: {
				show: true,
				type: "loading",
			},
		})
		wx.showNavigationBarLoading()
		wx.$API["home/getMenu"]({})
			.then((result) => {
				wx.hideNavigationBarLoading()
				wx.stopPullDownRefresh()
				const { data, enable } = result
				const userInfo = wx.getStorageSync("userInfo")

				data[0].list.forEach((v) => {
					if (userInfo.identityType == 4) {
						if (v.name == "学生学期生成报告") {
							v.name = "领导查询"
						}
					}
				})

				// data[1].list.forEach(v => {
				//   if (v.name == '文件代办') {
				//     deletev.name
				//     v.url
				//     v.menuId
				//     v.img
				//   }

				// });
				console.log(data, "data")
				data.forEach((item) => {
					item.list.forEach((si) => {
						si.param1List = si.param1 !== "/" ? si.param1.split("-") : []
					})
				})
				this.setData(
					{
						enable,
						menuData: data,
						picUrlArr: wx.getStorageSync("schoolConfig").picUrlArr,
						isShowView: true,
						"appMsg.show": false,
					},
					() => {},
				)
			})
			.catch((err) => {
				console.log(err)
				wx.hideNavigationBarLoading()
				wx.stopPullDownRefresh()
				this.setData({
					isShowView: true,
					appMsg: {
						show: true,
						type: "err",
					},
				})
			})
	},
	// 用户主动关闭公告
	closeNotice() {
		const noticeCache = wx.getStorageSync("noticeCache")
		wx.setStorage({
			key: "noticeCache",
			data: {
				...noticeCache,
				close: true,
			},
		})
		// wx.setStorageSync('noticeCache', {
		//   ...noticeCache,
		//   close: true,
		// })
	},
	/**
	 * @see 下拉刷新
	 */
	onPullDownRefresh() {
		this.getMenu()
	},
	/**
	 * @see 刷新获取菜单
	 */
	clickMsgButton() {
		this.getMenu()
	},
})
